/******************************************************************************
 * @File name   :      ReportController.java
 *
 * @Author      :      LUZHANG
 *
 * @Date        :      Sep 1, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2015 Capgemini, Inc. All  Rights Reserved.
 * This software is published under the terms of the Capgemini Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * Sep 1, 2015 5:55:54 PM        LUZHANG     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.report.controller;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.dealerinfosync.domain.DealerInfoRelMars;
import com.cap.bts.crmdp.dealer.logistic.constants.LogisticConstants;
import com.cap.bts.crmdp.dealer.logistic.dao.IMaintainLogisticDao;
import com.cap.bts.crmdp.dealer.logistic.dto.LogisticRelatedDto;
import com.cap.bts.crmdp.dealer.masterdata.domain.MasterDataDealerInfo;
import com.cap.bts.crmdp.dealer.masterdata.service.IMaintainDealerService;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainCarPlateDao;
import com.cap.bts.crmdp.dealer.member.domain.CarPlateInfo;
import com.cap.bts.crmdp.dealer.member.domain.MemberInfo;
import com.cap.bts.crmdp.dealer.member.service.IMaintainMemberService;
import com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberAndDealerInfoDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberPackagesReportDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberPackagesReportOfAllDealerDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto;
import com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService;
import com.cap.bts.crmdp.dealer.report.dto.InventoryResultDto;
import com.cap.bts.crmdp.dealer.report.dto.MemberChartDto;
import com.cap.bts.crmdp.dealer.report.dto.MemberChartResultDto;
import com.cap.bts.crmdp.dealer.report.dto.MemberReportResultDto;
import com.cap.bts.crmdp.dealer.report.dto.ReportQueryDto;
import com.cap.bts.crmdp.dealer.report.dto.SalesReportResultDto;
import com.cap.bts.crmdp.dealer.report.dto.TranHistoryDto;
import com.cap.bts.crmdp.dealer.report.service.IReportService;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.usermgnt.domain.User;

/**
 *
 */
@Controller
@RequestMapping(value = "/crmdp/dealer/report")
public class ReportController {

    static final String INVENTORYSTARTDATE = "inventoryStartDate";
    static final String INVENTORYENDDATE = "inventoryEndDate";
    static final String INVENTORYHIERARCHY = "inventoryHierarchy";
    static final String MEMBERSTARTDATE = "memberStartDate";
    static final String MEMBERENDDATE = "memberEndDate";
    static final String MEMBERPACKAGE = "memberPackage";
    static final String MEMBERHIERARCHY = "memberHierarchy";
    static final String SALESSTARTDATE = "salesStartDate";
    static final String SALESENDDATE = "salesEndDate";
    static final String SALESHIERARCHY = "salesHierarchy";
    static final String GETINVENTORYPAGE = "getInventoryPage";
    static final String GETINVENTORYCHART = "getInventoryChart";
    static final String GETMEMBERREPORTPAGE = "getMemberReportPage";
    static final String GETMEMBERCHART = "getMemberChart";
    static final String GETSALESREPORTPAGE = "getSalesPage";
    static final String GETSALESCHART = "getSalesChart";
    static final String RESULTLIST = "resultList";
    static final String SUMMARY = "summary";
    static final String INVENTORYREPORT = "/report/inventoryReport";
    static final String MEMBERREPORT = "/report/memberReport";
    static final String SALESREPORT = "/report/salesVolumeReport";
    static final String ALL_PACKAGE="packages.all";
    static final String YEARMONTHDAY="yyyy-MM-dd";
    static final String YEARMONTH="yyyy-MM";
    static final String DEALERID="dealerId";
    static final String DEALERLIST="dealerList";
    static final String DEFAULTHIERARCHY="1";
    static final String PACKAGELIST="packages";
    
    @Autowired
    IReportService reportService;
    @Resource(name = "maintainLogisticDao")
    private IMaintainLogisticDao maintainLogisticDao;
    @Autowired
    IRedemptionService redemptionService;
    @Autowired
    IMaintainMemberService maintainMemberService;
    @Autowired
    IMemberPackageService memberPackageService;

    @Resource(name = "maintainCarPlateDao")
    IMaintainCarPlateDao maintainCarPlateDao;
    
    @Autowired
    IMaintainDealerService maintainDealerServiceimpl;
    /**
     * 查询库存信息
     */
    @RequestMapping(value = "/toQueryInventoryPage")
    public String toQueryInventoryPage(ReportQueryDto dto, 
        Model model, HttpServletRequest request) throws AppException {
        User queryUser = UserUtil.getCurrentUser();
        InventoryResultDto result = new InventoryResultDto();
        if(queryUser!=null){
            dto.setUserId(Long.toString(queryUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                dto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    dto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, dto.getUserId());
        SimpleDateFormat df = new SimpleDateFormat(YEARMONTHDAY);
        SimpleDateFormat sdf = new SimpleDateFormat(YEARMONTH);
        Calendar cal = Calendar.getInstance();
        if(dto != null) {
            if(Utils.isNullOrEmpty(dto.getTransactionStartDate())){
                if(request.getSession().getAttribute(INVENTORYSTARTDATE) != null){
                    dto.setTransactionStartDate(request.getSession().getAttribute(INVENTORYSTARTDATE).toString());
                    }else{
                        dto.setTransactionStartDate(sdf.format(cal.getTime())+"-01");
                    }
            }
            if(Utils.isNullOrEmpty(dto.getTransactionEndDate())){
                if(request.getSession().getAttribute(INVENTORYENDDATE) != null){
                    dto.setTransactionEndDate(request.getSession().getAttribute(INVENTORYENDDATE).toString());
                    }else{
                        dto.setTransactionEndDate(df.format(cal.getTime()));
                    }
            }
            request.getSession().setAttribute(INVENTORYSTARTDATE, dto.getTransactionStartDate());
            request.getSession().setAttribute(INVENTORYENDDATE, dto.getTransactionEndDate());
            dto.setTransactionStartDate(request.getSession().getAttribute(INVENTORYSTARTDATE).toString());
            dto.setTransactionEndDate(request.getSession().getAttribute(INVENTORYENDDATE).toString());
            if(Utils.isNullOrEmpty(dto.getHierarchy())){
                if(request.getSession().getAttribute(INVENTORYHIERARCHY) == null){
                    dto.setHierarchy(dto.getUserId());
                }else{
                    dto.setHierarchy(request.getSession().getAttribute(INVENTORYHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(dto.getHierarchy())){
                dto.setHierarchy(maintainLogisticDao.getDealers(dto.getUserId()));
            }
            request.getSession().setAttribute(INVENTORYHIERARCHY, dto.getHierarchy());
            result = reportService.queryInventoryData(dto);
        }
        request.getSession().setAttribute(GETINVENTORYPAGE, dto);
        List<String> dealers = maintainLogisticDao.getDealerList(dto.getUserId());
        model.addAttribute(DEALERLIST, dealers);
        model.addAttribute(RESULTLIST, result.getResultList());
        model.addAttribute(SUMMARY, result.getResultSummary());
        model.addAttribute("dto", dto);
        return INVENTORYREPORT;
    }
    /**
     * 转向库存图表
     */
    @RequestMapping(value = "/toChartInventoryPage")
    public String toChartInventoryPage(ReportQueryDto dto, 
        Model model, HttpServletRequest request) throws AppException {
        User queryUser = UserUtil.getCurrentUser();
        if(queryUser!=null){
            dto.setUserId(Long.toString(queryUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                dto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    dto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, dto.getUserId());
        SimpleDateFormat d = new SimpleDateFormat(YEARMONTHDAY);
        SimpleDateFormat sd = new SimpleDateFormat(YEARMONTH);
        Calendar cl = Calendar.getInstance();
        if(dto != null) {
            if(Utils.isNullOrEmpty(dto.getTransactionStartDate())){
                if(request.getSession().getAttribute(INVENTORYSTARTDATE) == null){
                    dto.setTransactionStartDate(sd.format(cl.getTime())+"-01");
                    }else{
                        dto.setTransactionStartDate(request.getSession().getAttribute(INVENTORYSTARTDATE).toString());
                    }
            }
            if(Utils.isNullOrEmpty(dto.getTransactionEndDate())){
                if(request.getSession().getAttribute(INVENTORYENDDATE) == null){
                    dto.setTransactionEndDate(d.format(cl.getTime()));
                    }else{
                        dto.setTransactionEndDate(request.getSession().getAttribute(INVENTORYENDDATE).toString());
                    }
            }
            if(Utils.isNullOrEmpty(dto.getHierarchy())){
                if(request.getSession().getAttribute(INVENTORYHIERARCHY) == null){
                    dto.setHierarchy(dto.getUserId());
                }else{
                    dto.setHierarchy(request.getSession().getAttribute(INVENTORYHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(dto.getHierarchy())){
                dto.setHierarchy(maintainLogisticDao.getDealers(dto.getUserId()));
            }
            request.getSession().setAttribute(INVENTORYSTARTDATE, dto.getTransactionStartDate());
            request.getSession().setAttribute(INVENTORYENDDATE, dto.getTransactionEndDate());
            request.getSession().setAttribute(INVENTORYHIERARCHY, dto.getHierarchy());
        }
        model.addAttribute("dto", dto);
        List<String> dealers = maintainLogisticDao.getDealerList(dto.getUserId());
        model.addAttribute(DEALERLIST, dealers);
        return "/report/inventoryChart";
    }

    /**
     * 绘制库存图表
     */
    @RequestMapping(value = "/loadChartInventoryPage")
    @ResponseBody
    public String loadChartInventoryPage(ReportQueryDto dto, 
        Model model, HttpServletRequest request) throws AppException {
        User chartUser = UserUtil.getCurrentUser();
        StringBuilder result = new StringBuilder("[");
        if(chartUser!=null){
            dto.setUserId(Long.toString(chartUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                dto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    dto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, dto.getUserId());
        if(dto != null) {
            if((Utils.isNullOrEmpty(dto.getTransactionStartDate()))
                &&(request.getSession().getAttribute(INVENTORYSTARTDATE) != null)){
                    dto.setTransactionStartDate(request.getSession().getAttribute(INVENTORYSTARTDATE).toString());
            }
            if((Utils.isNullOrEmpty(dto.getTransactionEndDate()))
                &&(request.getSession().getAttribute(INVENTORYENDDATE) != null)){
                    dto.setTransactionEndDate(request.getSession().getAttribute(INVENTORYENDDATE).toString());
            }
            if(Utils.isNullOrEmpty(dto.getHierarchy())){
                if(request.getSession().getAttribute(INVENTORYHIERARCHY) == null){
                    dto.setHierarchy(dto.getUserId());
                }else{
                    dto.setHierarchy(request.getSession().getAttribute(INVENTORYHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(dto.getHierarchy())){
                dto.setHierarchy(maintainLogisticDao.getDealers(dto.getUserId()));
            }
            request.getSession().setAttribute(INVENTORYSTARTDATE, dto.getTransactionStartDate());
            request.getSession().setAttribute(INVENTORYENDDATE, dto.getTransactionEndDate());
            request.getSession().setAttribute(INVENTORYHIERARCHY, dto.getHierarchy());
            result.append(reportService.queryInventoryDataForChart(dto));
        }
        result.append("]");
        request.getSession().setAttribute(GETINVENTORYCHART, result.toString());
        String json="";
        try {
            json = java.net.URLEncoder.encode(result.toString(),
                LogisticConstants.ENCODE_UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new AppException("inventoryChart", e);
        }
        return json.replaceAll("%2C",",").replaceAll("%3A", ":");
    }

    @RequestMapping(value = "/loadCardNames")
    @ResponseBody
    public String loadCardNames(ReportQueryDto dto, 
        Model model, HttpServletRequest request) throws AppException {
        User loadCardUser = UserUtil.getCurrentUser();
        StringBuilder result = new StringBuilder("[");
        if(loadCardUser!=null){
            dto.setUserId(Long.toString(loadCardUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                dto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    dto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, dto.getUserId());
        if(dto != null) {
            if((Utils.isNullOrEmpty(dto.getTransactionStartDate()))
                &&(request.getSession().getAttribute(INVENTORYSTARTDATE) != null)){
                    dto.setTransactionStartDate(request.getSession().getAttribute(INVENTORYSTARTDATE).toString());
            }
            if((Utils.isNullOrEmpty(dto.getTransactionEndDate()))
                &&(request.getSession().getAttribute(INVENTORYENDDATE) != null)){
                    dto.setTransactionEndDate(request.getSession().getAttribute(INVENTORYENDDATE).toString());
            }
            if(Utils.isNullOrEmpty(dto.getHierarchy())){
                if(request.getSession().getAttribute(INVENTORYHIERARCHY) == null){
                    dto.setHierarchy(dto.getUserId());
                }else{
                    dto.setHierarchy(request.getSession().getAttribute(INVENTORYHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(dto.getHierarchy())){
                dto.setHierarchy(maintainLogisticDao.getDealers(dto.getUserId()));
            }
            request.getSession().setAttribute(INVENTORYSTARTDATE, dto.getTransactionStartDate());
            request.getSession().setAttribute(INVENTORYENDDATE, dto.getTransactionEndDate());
            request.getSession().setAttribute(INVENTORYHIERARCHY, dto.getHierarchy());
            List<LogisticRelatedDto> dataList = maintainLogisticDao.getSelledCard(dto);
            for(int i=0;i<dataList.size();i++){
                result.append("\"").append(dataList.get(i).getCardName()).append("\",");
                }
        }
        result.delete(result.length()-1, result.length()).append("]");
        request.getSession().setAttribute(GETINVENTORYCHART, result.toString());
        String json="";
        try {
            json = java.net.URLEncoder.encode(result.toString(),
                LogisticConstants.ENCODE_UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new AppException("inventoryChart", e);
        }
        return json.replaceAll("%2C",",");
    }
    /**
     * 返回查询库存
     */
    @RequestMapping(value = "/backToInventoryPage")
    public String backToInventoryPage(Model model, HttpServletRequest request) throws AppException {
        ReportQueryDto backToDto = new ReportQueryDto();
        InventoryResultDto backToResult = new InventoryResultDto();
        User queryUser = UserUtil.getCurrentUser();
        if(queryUser!=null){
            backToDto.setUserId(Long.toString(queryUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                backToDto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    backToDto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, backToDto.getUserId());
        if(request.getSession().getAttribute(INVENTORYSTARTDATE) != null){
            backToDto.setTransactionStartDate(request.getSession().getAttribute(INVENTORYSTARTDATE).toString());
            }
        if(request.getSession().getAttribute(INVENTORYENDDATE) != null){
            backToDto.setTransactionEndDate(request.getSession().getAttribute(INVENTORYENDDATE).toString());
            }
        SimpleDateFormat backdf = new SimpleDateFormat(YEARMONTHDAY);
        SimpleDateFormat sbackdf = new SimpleDateFormat(YEARMONTH);
        Calendar cal = Calendar.getInstance();
        if(backToDto != null) {
            if(Utils.isNullOrEmpty(backToDto.getTransactionStartDate())){
                if(request.getSession().getAttribute(INVENTORYSTARTDATE) != null){
                    backToDto.setTransactionStartDate(request.getSession().getAttribute(INVENTORYSTARTDATE).toString());
                    }else{
                        backToDto.setTransactionStartDate(sbackdf.format(cal.getTime())+"-01");
                    }
            }
            if(Utils.isNullOrEmpty(backToDto.getTransactionEndDate())){
                if(request.getSession().getAttribute(INVENTORYENDDATE) != null){
                    backToDto.setTransactionEndDate(request.getSession().getAttribute(INVENTORYENDDATE).toString());
                    }else{
                        backToDto.setTransactionEndDate(backdf.format(cal.getTime()));
                    }
            }
            if(Utils.isNullOrEmpty(backToDto.getHierarchy())){
                if(request.getSession().getAttribute(INVENTORYHIERARCHY) == null){
                    backToDto.setHierarchy(backToDto.getUserId());
                }else{
                    backToDto.setHierarchy(request.getSession().getAttribute(INVENTORYHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(backToDto.getHierarchy())){
                backToDto.setHierarchy(maintainLogisticDao.getDealers(backToDto.getUserId()));
            }
            request.getSession().setAttribute(INVENTORYHIERARCHY, backToDto.getHierarchy());
            request.getSession().setAttribute(INVENTORYSTARTDATE, backToDto.getTransactionStartDate());
            request.getSession().setAttribute(INVENTORYENDDATE, backToDto.getTransactionEndDate());
            backToDto.setTransactionStartDate(request.getSession().getAttribute(INVENTORYSTARTDATE).toString());
            backToDto.setTransactionEndDate(request.getSession().getAttribute(INVENTORYENDDATE).toString());
            backToResult = reportService.queryInventoryData(backToDto);
        }
        request.getSession().setAttribute(GETINVENTORYPAGE, backToDto);
        List<String> dealers = maintainLogisticDao.getDealerList(backToDto.getUserId());
        model.addAttribute(DEALERLIST, dealers);
        model.addAttribute(RESULTLIST, backToResult.getResultList());
        model.addAttribute(SUMMARY, backToResult.getResultSummary());
        model.addAttribute("dto", backToDto);
        return INVENTORYREPORT;
    }
    /**
     * 查询新增数据
     */
    @RequestMapping(value = "/toQueryMemberReport")
    public String toQueryMemberReport(ReportQueryDto mbrDto, 
        Model model, HttpServletRequest request) throws AppException {
        User queryMemberUser = UserUtil.getCurrentUser();
        MemberReportResultDto result = new MemberReportResultDto();
        //MemberReportResultDto details= new MemberReportResultDto()
        if(queryMemberUser!=null){
            mbrDto.setUserId(Long.toString(queryMemberUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                mbrDto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    mbrDto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, mbrDto.getUserId());
        SimpleDateFormat newdf = new SimpleDateFormat(YEARMONTHDAY);
        SimpleDateFormat snewdf = new SimpleDateFormat(YEARMONTH);
        Calendar mbrCal = Calendar.getInstance();
        if(mbrDto != null) {
            if(Utils.isNullOrEmpty(mbrDto.getTransactionStartDate())){
                if(request.getSession().getAttribute(MEMBERSTARTDATE) != null){
                    mbrDto.setTransactionStartDate(request.getSession().getAttribute(MEMBERSTARTDATE).toString());
                    }else{
                        mbrDto.setTransactionStartDate(snewdf.format(mbrCal.getTime())+"-01");
                    }
            }
            if(Utils.isNullOrEmpty(mbrDto.getTransactionEndDate())){
                if(request.getSession().getAttribute(MEMBERENDDATE) != null){
                    mbrDto.setTransactionEndDate(request.getSession().getAttribute(MEMBERENDDATE).toString());
                    }else{
                        mbrDto.setTransactionEndDate(newdf.format(mbrCal.getTime()));
                    }
            }
            if(Utils.isNullOrEmpty(mbrDto.getHierarchy())){
                if(request.getSession().getAttribute(MEMBERHIERARCHY) == null){
                    mbrDto.setHierarchy(mbrDto.getUserId());
                }else{
                    mbrDto.setHierarchy(request.getSession().getAttribute(MEMBERHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(mbrDto.getHierarchy())){
                mbrDto.setHierarchy(maintainLogisticDao.getDealers(mbrDto.getUserId()));
            }
            if(Utils.isNullOrEmpty(mbrDto.getPackageId())){
                if(request.getSession().getAttribute(MEMBERPACKAGE) == null){
                    mbrDto.setPackageId("all");
                }else{
                    mbrDto.setPackageId(request.getSession().getAttribute(MEMBERPACKAGE).toString());
                }
            }
            request.getSession().setAttribute(MEMBERPACKAGE, mbrDto.getPackageId());
            request.getSession().setAttribute(MEMBERHIERARCHY, mbrDto.getHierarchy());
            request.getSession().setAttribute(MEMBERSTARTDATE, mbrDto.getTransactionStartDate());
            request.getSession().setAttribute(MEMBERENDDATE, mbrDto.getTransactionEndDate());
            mbrDto.setTransactionStartDate(request.getSession().getAttribute(MEMBERSTARTDATE).toString());
            mbrDto.setTransactionEndDate(request.getSession().getAttribute(MEMBERENDDATE).toString());
            result = reportService.queryMemberData(mbrDto);
            //details = reportService.queryMemberDetails(mbrDto)
        }
        request.getSession().setAttribute(GETMEMBERREPORTPAGE, mbrDto);
        List<LogisticRelatedDto> packages = maintainLogisticDao.getPackageName();
        model.addAttribute(PACKAGELIST, packages);
        List<String> dealers = maintainLogisticDao.getDealerList(mbrDto.getUserId());
        model.addAttribute(DEALERLIST, dealers);
        model.addAttribute(RESULTLIST, result.getResult());
        /*model.addAttribute("newMember", details.getResultListMmbr())
        model.addAttribute("newPackage", details.getResultListPkg())
        model.addAttribute("newCar", details.getResultListCr())*/
        model.addAttribute("dto", mbrDto);
        return MEMBERREPORT;
    }

    /**
     * 转向新增数据图表
     */
    @RequestMapping(value = "/toChartMemberPage")
    public String toChartMemberPage(ReportQueryDto dto, 
        Model model, HttpServletRequest request) throws AppException {
        User queryMemberUser = UserUtil.getCurrentUser();
        if(queryMemberUser!=null){
            dto.setUserId(Long.toString(queryMemberUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                dto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    dto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, dto.getUserId());
        SimpleDateFormat d = new SimpleDateFormat(YEARMONTHDAY);
        SimpleDateFormat sd = new SimpleDateFormat(YEARMONTH);
        Calendar cl = Calendar.getInstance();
        if(dto != null) {
            if(Utils.isNullOrEmpty(dto.getTransactionStartDate())){
                if(request.getSession().getAttribute(MEMBERSTARTDATE) == null){
                    dto.setTransactionStartDate(sd.format(cl.getTime())+"-01");
                    }else{
                        dto.setTransactionStartDate(request.getSession().getAttribute(MEMBERSTARTDATE).toString());
                    }
            }
            if(Utils.isNullOrEmpty(dto.getTransactionEndDate())){
                if(request.getSession().getAttribute(MEMBERENDDATE) == null){
                    dto.setTransactionEndDate(d.format(cl.getTime()));
                    }else{
                        dto.setTransactionEndDate(request.getSession().getAttribute(MEMBERENDDATE).toString());
                    }
            }
            if(Utils.isNullOrEmpty(dto.getHierarchy())){
                if(request.getSession().getAttribute(MEMBERHIERARCHY) == null){
                    dto.setHierarchy(dto.getUserId());
                }else{
                    dto.setHierarchy(request.getSession().getAttribute(MEMBERHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(dto.getHierarchy())){
                dto.setHierarchy(maintainLogisticDao.getDealers(dto.getUserId()));
            }
            if(Utils.isNullOrEmpty(dto.getPackageId())){
                if(request.getSession().getAttribute(MEMBERPACKAGE) == null){
                    dto.setPackageId("all");
                }else{
                    dto.setPackageId(request.getSession().getAttribute(MEMBERPACKAGE).toString());
                }
            }
            request.getSession().setAttribute(MEMBERPACKAGE, dto.getPackageId());
            request.getSession().setAttribute(MEMBERHIERARCHY, dto.getHierarchy());
            request.getSession().setAttribute(MEMBERSTARTDATE, dto.getTransactionStartDate());
            request.getSession().setAttribute(MEMBERENDDATE, dto.getTransactionEndDate());
        }
        List<LogisticRelatedDto> packagesForChart = maintainLogisticDao.getPackageName();
        model.addAttribute(PACKAGELIST, packagesForChart);
        List<String> dealers = maintainLogisticDao.getDealerList(dto.getUserId());
        model.addAttribute(DEALERLIST, dealers);
        model.addAttribute("dto", dto);
        return "/report/memberChart";
    }

    /**
     * 绘制新增数据图表
     */
    @RequestMapping(value = "/loadChartMemberPage")
    @ResponseBody
    public List<MemberChartDto> loadChartMemberPage(ReportQueryDto memberChartDto, 
        Model model, HttpServletRequest request) throws AppException {
        User memberChartUser = UserUtil.getCurrentUser();
        MemberChartResultDto result = new MemberChartResultDto();
        if(memberChartUser!=null){
            memberChartDto.setUserId(Long.toString(memberChartUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                memberChartDto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    memberChartDto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, memberChartDto.getUserId());
        if(memberChartDto != null) {
            if((Utils.isNullOrEmpty(memberChartDto.getTransactionStartDate()))
                &&(request.getSession().getAttribute(MEMBERSTARTDATE) != null)){
                    memberChartDto.setTransactionStartDate(request.getSession().getAttribute(MEMBERSTARTDATE).toString());
            }
            if((Utils.isNullOrEmpty(memberChartDto.getTransactionEndDate()))
                &&(request.getSession().getAttribute(MEMBERENDDATE) != null)){
                    memberChartDto.setTransactionEndDate(request.getSession().getAttribute(MEMBERENDDATE).toString());
            }
            if(Utils.isNullOrEmpty(memberChartDto.getHierarchy())){
                if(request.getSession().getAttribute(MEMBERHIERARCHY) == null){
                    memberChartDto.setHierarchy(memberChartDto.getUserId());
                }else{
                    memberChartDto.setHierarchy(request.getSession().getAttribute(MEMBERHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(memberChartDto.getHierarchy())){
                memberChartDto.setHierarchy(maintainLogisticDao.getDealers(memberChartDto.getUserId()));
            }
            if(Utils.isNullOrEmpty(memberChartDto.getPackageId())){
                if(request.getSession().getAttribute(MEMBERPACKAGE) == null){
                    memberChartDto.setPackageId("all");
                }else{
                    memberChartDto.setPackageId(request.getSession().getAttribute(MEMBERPACKAGE).toString());
                }
            }
            request.getSession().setAttribute(MEMBERPACKAGE, memberChartDto.getPackageId());
            request.getSession().setAttribute(MEMBERHIERARCHY, memberChartDto.getHierarchy());
            request.getSession().setAttribute(MEMBERSTARTDATE, memberChartDto.getTransactionStartDate());
            request.getSession().setAttribute(MEMBERENDDATE, memberChartDto.getTransactionEndDate());
            result=reportService.queryMemberDataForChart(memberChartDto);
        }
        request.getSession().setAttribute(GETMEMBERCHART, result.toString());
        List<MemberChartDto> memberChart = new ArrayList<MemberChartDto>();
        memberChart=result.getMemberChartData();
        return memberChart;
    }
    
    @RequestMapping(value = "/loadChartInventoryMax")
    @ResponseBody
    public String loadChartInventoryMax(ReportQueryDto maxMemberNumDto, 
        Model model, HttpServletRequest request) throws AppException {
        User memberChartUser = UserUtil.getCurrentUser();
        String maxResult = "";
        if(memberChartUser!=null){
            maxMemberNumDto.setUserId(Long.toString(memberChartUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                maxMemberNumDto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    maxMemberNumDto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, maxMemberNumDto.getUserId());
        if(maxMemberNumDto != null) {
            if((Utils.isNullOrEmpty(maxMemberNumDto.getTransactionStartDate()))
                &&(request.getSession().getAttribute(MEMBERSTARTDATE) != null)){
                    maxMemberNumDto.setTransactionStartDate(request.getSession().getAttribute(MEMBERSTARTDATE).toString());
            }
            if((Utils.isNullOrEmpty(maxMemberNumDto.getTransactionEndDate()))
                &&(request.getSession().getAttribute(MEMBERENDDATE) != null)){
                    maxMemberNumDto.setTransactionEndDate(request.getSession().getAttribute(MEMBERENDDATE).toString());
            }
            if(Utils.isNullOrEmpty(maxMemberNumDto.getHierarchy())){
                if(request.getSession().getAttribute(MEMBERHIERARCHY) == null){
                    maxMemberNumDto.setHierarchy(maxMemberNumDto.getUserId());
                }else{
                    maxMemberNumDto.setHierarchy(request.getSession().getAttribute(MEMBERHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(maxMemberNumDto.getHierarchy())){
                maxMemberNumDto.setHierarchy(maintainLogisticDao.getDealers(maxMemberNumDto.getUserId()));
            }
            if(Utils.isNullOrEmpty(maxMemberNumDto.getPackageId())){
                if(request.getSession().getAttribute(MEMBERPACKAGE) == null){
                    maxMemberNumDto.setPackageId("all");
                }else{
                    maxMemberNumDto.setPackageId(request.getSession().getAttribute(MEMBERPACKAGE).toString());
                }
            }
            request.getSession().setAttribute(MEMBERPACKAGE, maxMemberNumDto.getPackageId());
            request.getSession().setAttribute(MEMBERHIERARCHY, maxMemberNumDto.getHierarchy());
            request.getSession().setAttribute(MEMBERSTARTDATE, maxMemberNumDto.getTransactionStartDate());
            request.getSession().setAttribute(MEMBERENDDATE, maxMemberNumDto.getTransactionEndDate());
            List<Integer> maxList = reportService.queryMemberDataForChart(maxMemberNumDto).getMaxList();
            int max=Collections.max(maxList);
            max=(max/10)*10+10;
            maxResult = String.valueOf(max);
        }
        request.getSession().setAttribute(GETMEMBERCHART, maxResult);
        return maxResult;
    }
    /**
     * 返回查询新增数据
     */
    @RequestMapping(value = "/backToMemberReportPage")
    public String backToMemberReportPage(Model model, HttpServletRequest request) throws AppException {
        ReportQueryDto backDto = new ReportQueryDto();
        MemberReportResultDto backResult = new MemberReportResultDto();
        //MemberReportResultDto backDetails= new MemberReportResultDto()
        User queryUser = UserUtil.getCurrentUser();
        if(queryUser!=null){
            backDto.setUserId(Long.toString(queryUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                backDto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    backDto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, backDto.getUserId());
        if(request.getSession().getAttribute(MEMBERSTARTDATE) != null){
            backDto.setTransactionStartDate(request.getSession().getAttribute(MEMBERSTARTDATE).toString());
            }
        if(request.getSession().getAttribute(MEMBERENDDATE) != null){
            backDto.setTransactionEndDate(request.getSession().getAttribute(MEMBERENDDATE).toString());
            }
        SimpleDateFormat backd = new SimpleDateFormat(YEARMONTHDAY);
        SimpleDateFormat sbackd = new SimpleDateFormat(YEARMONTH);
        Calendar backCal = Calendar.getInstance();
        if(backDto != null) {
            if(Utils.isNullOrEmpty(backDto.getTransactionStartDate())){
                if(request.getSession().getAttribute(MEMBERSTARTDATE) != null){
                    backDto.setTransactionStartDate(request.getSession().getAttribute(MEMBERSTARTDATE).toString());
                    }else{
                        backDto.setTransactionStartDate(sbackd.format(backCal.getTime())+"-01");
                    }
            }
            if(Utils.isNullOrEmpty(backDto.getTransactionEndDate())){
                if(request.getSession().getAttribute(MEMBERENDDATE) != null){
                    backDto.setTransactionEndDate(request.getSession().getAttribute(MEMBERENDDATE).toString());
                    }else{
                        backDto.setTransactionEndDate(backd.format(backCal.getTime()));
                    }
            }
            if(Utils.isNullOrEmpty(backDto.getHierarchy())){
                if(request.getSession().getAttribute(MEMBERHIERARCHY) == null){
                    backDto.setHierarchy(backDto.getUserId());
                }else{
                    backDto.setHierarchy(request.getSession().getAttribute(MEMBERHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(backDto.getHierarchy())){
                backDto.setHierarchy(maintainLogisticDao.getDealers(backDto.getUserId()));
            }
            if(Utils.isNullOrEmpty(backDto.getPackageId())){
                if(request.getSession().getAttribute(MEMBERPACKAGE) == null){
                    backDto.setPackageId("all");
                }else{
                    backDto.setPackageId(request.getSession().getAttribute(MEMBERPACKAGE).toString());
                }
            }
            request.getSession().setAttribute(MEMBERPACKAGE, backDto.getPackageId());
            request.getSession().setAttribute(MEMBERHIERARCHY, backDto.getHierarchy());
            request.getSession().setAttribute(MEMBERSTARTDATE, backDto.getTransactionStartDate());
            request.getSession().setAttribute(MEMBERENDDATE, backDto.getTransactionEndDate());
            backDto.setTransactionStartDate(request.getSession().getAttribute(MEMBERSTARTDATE).toString());
            backDto.setTransactionEndDate(request.getSession().getAttribute(MEMBERENDDATE).toString());
            backResult = reportService.queryMemberData(backDto);
            //backDetails = reportService.queryMemberDetails(backDto)
        }
        request.getSession().setAttribute(GETMEMBERREPORTPAGE, backDto);
        List<LogisticRelatedDto> backPackages = maintainLogisticDao.getPackageName();
        model.addAttribute(PACKAGELIST, backPackages);
        List<String> dealers = maintainLogisticDao.getDealerList(backDto.getUserId());
        model.addAttribute(DEALERLIST, dealers);
        model.addAttribute(RESULTLIST, backResult.getResult());
        /*model.addAttribute("newMember", backDetails.getResultListMmbr())
        model.addAttribute("newPackage", backDetails.getResultListPkg())
        model.addAttribute("newCar", backDetails.getResultListCr())*/
        model.addAttribute("dto", backDto);
        return MEMBERREPORT;
    }

    
    @RequestMapping(value = "/showMemberPackagesReport")
    public String showMemberPackagesReport(MemberQueryDto dto,Model model, HttpServletRequest request) throws AppException {
        List<MemberPackagesReportDto> list=redemptionService.getPackageListForReportByMember(dto);
        
        List<MemberAndDealerInfoDto> memberAndDealerInfoDtoList = redemptionService.getMemberAndDealerInfoDtoByMemberId(dto.getId());
        MemberAndDealerInfoDto memberAndDealerInfoDto = new MemberAndDealerInfoDto();
        if(memberAndDealerInfoDtoList !=null && !memberAndDealerInfoDtoList.isEmpty()){
            memberAndDealerInfoDto = memberAndDealerInfoDtoList.get(0);
        }
        
        model.addAttribute("memberPackageInfoList", list);
        model.addAttribute("memberInfo", memberAndDealerInfoDto);
        model.addAttribute("submitDto", dto);
        com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto memberQueryDto = 
            (com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto) request.getSession().getAttribute("getMaintainMemberPage");
        if(memberQueryDto != null){
            memberQueryDto.setIsSelected("radio"+ dto.getId() +dto.getCarPlate() +"Rad");
        }
        return "/report/showMemberPackagesReport";
    }   
    
    @RequestMapping(value = "/showMemberPackagesReportForMars")
    public String showMemberPackagesReportForMars(Long dealerId,String marsMemberId, String carMarsId, Model model, HttpServletRequest request) throws AppException {
        MemberQueryDto dto = new MemberQueryDto();
        Long carId = null;
        if(StringUtils.isNotBlank(carMarsId)){
//        	CarPlateInfo carPlateInfo = maintainCarPlateDao.getCarPlateInfoByMarsCarId(carMarsId);
        	List<CarPlateInfo> list =  maintainCarPlateDao.getCarPlateInfoListByCarPlateForMars(dealerId, carMarsId);
        	if(list != null && !list.isEmpty()){
        		carId = list.get(0).getId();
        	}else{
        		model.addAttribute("errorType", "carMarsIdNotExist");
        		return "/report/ReportForMarsError";
        	}
        }
        
        
        
        
        List<MemberAndDealerInfoDto> memberAndDealerInfoDtoList = memberPackageService.getMemberAndDealerInfoDtoByMARSIdAndDearId(dealerId, marsMemberId);
        MemberAndDealerInfoDto memberAndDealerInfoDto = new MemberAndDealerInfoDto();
        if(memberAndDealerInfoDtoList !=null && !memberAndDealerInfoDtoList.isEmpty()){
            memberAndDealerInfoDto = memberAndDealerInfoDtoList.get(0);
        }else{
        	model.addAttribute("errorType", "marsMemberIdNotExist");
        	return "/report/ReportForMarsError";
        }
        
        if(memberAndDealerInfoDto != null){
        	dto.setId(memberAndDealerInfoDto.getId());
        	List<MemberPackagesReportDto> list = memberPackageService.getPackageListForReportByMember(memberAndDealerInfoDto.getId(), carId);
        	
        	model.addAttribute("memberPackageInfoList", list);
            
        }
        
        model.addAttribute("carMarsId",carMarsId);      
        model.addAttribute("dealerId",dealerId);      
        model.addAttribute("marsMemberId",marsMemberId);      
        model.addAttribute("memberInfo", memberAndDealerInfoDto);
        model.addAttribute("submitDto", dto);
        return "/report/showMemberPackagesReportForMars";
    }  
    
    
    
    @RequestMapping(value = "/showMemberPackagesReportForMarsAll")
    public String showMemberPackagesReportForMarsAll(Long dealerId, String marsMemberId, String carMarsId, Model model, String isAll, HttpServletRequest request) throws AppException {
    	List<String> idList = new ArrayList<String>();
    	if(StringUtils.equals(isAll, "1")){
    		isAll = "0";
    		List<DealerInfoRelMars> dealerInfoRelMarsList = redemptionService.getMarsTenantIdByDealerId(dealerId);
        	
        	if(dealerInfoRelMarsList != null &&  !dealerInfoRelMarsList.isEmpty()){
        		List<Integer> list = redemptionService.getDealerIdByMarsTenantId(dealerInfoRelMarsList.get(0).getMarsTenantId());
        		
        		for (Integer id : list) {
        			idList.add(id + "");
    			}
        	}
    	}else{
    		isAll = "1";
    		idList.add(dealerId + "");
    	}
    	
    		
    	List<MasterDataDealerInfo>  dealerInfoList = maintainDealerServiceimpl.getDearlerIntoByDealerIds(idList);
        	
        model.addAttribute("dealerInfoList", dealerInfoList);
        	
        
        model.addAttribute("isAll", isAll);      
        model.addAttribute("carMarsId",carMarsId);      
        model.addAttribute("dealerId",dealerId);      
        model.addAttribute("marsMemberId",marsMemberId);      
        return "/mars/showMemberPackagesReportForMarsAll";
    }  
    
    
    
    @RequestMapping(value = "/showMemberPackagesForAllDealerReportForMars")
    public String showMemberPackagesForAllDealerReportForMars(Long dealerId,String marsMemberId, String carMarsId, Model model, HttpServletRequest request) throws AppException {
        MemberQueryDto dto = new MemberQueryDto();
        Long carId = null;
        
        MemberInfo allMemberInfo = null;
        List<String> noMemeberDealerIdList = new ArrayList<String>();
        
        if(StringUtils.isNotBlank(carMarsId)){
//            CarPlateInfo carPlateInfo = maintainCarPlateDao.getCarPlateInfoByMarsCarId(carMarsId);
            CarPlateInfo carPlateInfo = maintainCarPlateDao.getCarPlateInfoByMarsCarIdAndMarsMemberId(carMarsId, marsMemberId);
            if(carPlateInfo != null){
                carId = carPlateInfo.getId();
            }
        }
        List<DealerInfoRelMars> dealerInfoRelMarsList = redemptionService.getMarsTenantIdByDealerId(dealerId);
        List<MemberInfo> memberList = new ArrayList<MemberInfo>();
        if(dealerInfoRelMarsList != null && !dealerInfoRelMarsList.isEmpty()){
            List<MemberAndDealerInfoDto> memberAndDealerInfoDtoList = memberPackageService.getMemberAndDealerInfoDtoByMARSIdAndDearId(dealerId, marsMemberId);
            MemberAndDealerInfoDto memberAndDealerInfoDto = new MemberAndDealerInfoDto();
            String mobile = null;
            if(memberAndDealerInfoDtoList !=null && !memberAndDealerInfoDtoList.isEmpty()){
                memberAndDealerInfoDto = memberAndDealerInfoDtoList.get(0);
                mobile = memberAndDealerInfoDto.getMobilePhone();
            }
            String marsTenantId = dealerInfoRelMarsList.get(0).getMarsTenantId();
            List<Integer> list = redemptionService.getDealerIdByMarsTenantId(marsTenantId);
            if(list != null && !list.isEmpty()){
                for(int i=0;i<list.size(); i++){
                    MemberInfo memberInfo = new MemberInfo();
                    memberInfo = maintainMemberService.getMemberByDealerIdAndMARSMemberId(list.get(i).longValue(), marsMemberId);
                    if(memberInfo != null){
                        memberList.add(memberInfo);
                        allMemberInfo = memberInfo;
                    }
                    //@annson
                    else{
                    	noMemeberDealerIdList.add(list.get(i) + "");
                    }
                }
            }
        }
        if(memberList != null && !memberList.isEmpty()){
            List<MemberPackagesReportOfAllDealerDto> resultForAlldealer = new ArrayList<MemberPackagesReportOfAllDealerDto>();
            for(int i=0; i<memberList.size(); i++){
                MemberPackagesReportOfAllDealerDto memberPackagesReportOfAllDealerDto = new MemberPackagesReportOfAllDealerDto();
                MemberQueryDto memberQueryDto = new MemberQueryDto();
                memberQueryDto.setId(memberList.get(i).getId());
                List<MemberPackagesReportDto> list=redemptionService.getPackageListForReportByMember(memberQueryDto);
                List<MemberAndDealerInfoDto> memberAndDealerInfoDtoList = redemptionService.getMemberAndDealerInfoDtoByMemberId(memberQueryDto.getId());
                MemberAndDealerInfoDto memberAndDealerInfoDto = new MemberAndDealerInfoDto();
                if(memberAndDealerInfoDtoList !=null && !memberAndDealerInfoDtoList.isEmpty()){
                    memberAndDealerInfoDto = memberAndDealerInfoDtoList.get(0);
                }
                memberPackagesReportOfAllDealerDto.setMemberPackagesReportDtoList(list);
                memberPackagesReportOfAllDealerDto.setMemberAndDealerInfoDto(memberAndDealerInfoDto);
                resultForAlldealer.add(memberPackagesReportOfAllDealerDto);
            }
            model.addAttribute("carMarsId",carMarsId);      
            model.addAttribute("dealerId",dealerId);      
            model.addAttribute("marsMemberId",marsMemberId); 
            model.addAttribute("resultForAlldealer", resultForAlldealer);
            model.addAttribute("submitDto", dto);
        }else{
            List<MemberPackagesReportOfAllDealerDto> resultForAlldealer = new ArrayList<MemberPackagesReportOfAllDealerDto>();
            MemberPackagesReportOfAllDealerDto memberPackagesReportOfAllDealerDto = new MemberPackagesReportOfAllDealerDto();
            List<MemberAndDealerInfoDto> memberAndDealerInfoDtoList = memberPackageService.getMemberAndDealerInfoDtoByMARSIdAndDearId(dealerId, marsMemberId);
            MemberAndDealerInfoDto memberAndDealerInfoDto = new MemberAndDealerInfoDto();
            if(memberAndDealerInfoDtoList !=null && !memberAndDealerInfoDtoList.isEmpty()){
                memberAndDealerInfoDto = memberAndDealerInfoDtoList.get(0);
                memberPackagesReportOfAllDealerDto.setMemberAndDealerInfoDto(memberAndDealerInfoDto);
            }
            
            if(memberAndDealerInfoDto != null){
                dto.setId(memberAndDealerInfoDto.getId());
                List<MemberPackagesReportDto> list = memberPackageService.getPackageListForReportByMember(memberAndDealerInfoDto.getId(), carId);
                memberPackagesReportOfAllDealerDto.setMemberPackagesReportDtoList(list);
            }
            resultForAlldealer.add(memberPackagesReportOfAllDealerDto);
            model.addAttribute("carMarsId",carMarsId);      
            model.addAttribute("dealerId",dealerId);      
            model.addAttribute("marsMemberId",marsMemberId); 
            model.addAttribute("resultForAlldealer", resultForAlldealer);
            model.addAttribute("submitDto", dto);
        }
        
        //@annson
        if(!noMemeberDealerIdList.isEmpty()){
        	model.addAttribute("memberInfo", allMemberInfo);
        	
        	List<MasterDataDealerInfo>  noMemberDealerInfoList = maintainDealerServiceimpl.getDearlerIntoByDealerIds(noMemeberDealerIdList);
        	
        	model.addAttribute("noMemberDealerInfoList", noMemberDealerInfoList);
        }
        
        return "/report/showMemberPackagesForAllDealerReportForMars";
    }
    
    @RequestMapping(value = "/printMemberPackagesReport")
    public String printMemberPackagesReport(MemberQueryDto dto,Model model, HttpServletRequest request) throws AppException {
        List<MemberPackagesReportDto> list=redemptionService.getPackageListForReportByMember(dto);
        List<MemberAndDealerInfoDto> memberAndDealerInfoDtoList = redemptionService.getDealerInfoDto();
        MemberAndDealerInfoDto memberAndDealerInfoDto = new MemberAndDealerInfoDto();
        if(memberAndDealerInfoDtoList !=null && !memberAndDealerInfoDtoList.isEmpty()){
            memberAndDealerInfoDto = memberAndDealerInfoDtoList.get(0);
            memberAndDealerInfoDto.setMemberName(dto.getMemberName());
            memberAndDealerInfoDto.setMobilePhone(dto.getMobilePhone());
        }
        
        model.addAttribute("memberPackageInfoList", list);
        model.addAttribute("memberInfo", memberAndDealerInfoDto);
        model.addAttribute("submitDto", dto);
        com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto memberQueryDto = 
            (com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto) request.getSession().getAttribute("getMaintainMemberPage");
        memberQueryDto.setIsSelected("radio"+ dto.getId() +dto.getCarPlate() +"Rad");
        return "/report/printMemberPackagesReport";
    }   
    
    /**
     * 查看会员交易历史明细
     * @Date        :      Sep 26, 2015
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "/toTransactionHistory")
    public String toTransactionHistory(MemberQueryDto dto,Model model, HttpServletRequest request) throws AppException {
        List<TranHistoryDto> list=reportService.queryTranHistoryListByMemberId(dto.getId(), UserUtil.getCurrentUser().getDealerId(),dto.getCarPlate());
        List<MemberAndDealerInfoDto> memberAndDealerInfoDtoList = redemptionService.getDealerInfoDto();
        MemberAndDealerInfoDto memberAndDealerInfoDto = new MemberAndDealerInfoDto();
        if(memberAndDealerInfoDtoList !=null && !memberAndDealerInfoDtoList.isEmpty()){
            memberAndDealerInfoDto = memberAndDealerInfoDtoList.get(0);
            memberAndDealerInfoDto.setMemberName(dto.getMemberName());
            memberAndDealerInfoDto.setMobilePhone(dto.getMobilePhone());
        }
        com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto memberQueryDto = 
            (com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto) request.getSession().getAttribute("getMaintainMemberPage");
        memberQueryDto.setIsSelected("radio"+ dto.getId() +dto.getCarPlate() +"Rad");
        model.addAttribute("memberInfo", memberAndDealerInfoDto);
        model.addAttribute("TranHistoryDtoList", list);
        model.addAttribute("dto", dto);
        return "/report/transactionHistory";
    }
    
    /**
     * 查询套餐销售额
     */
    @RequestMapping(value = "/toQuerySalesReport")
    public String toQuerySalesReport(ReportQueryDto salesDto, 
        Model model, HttpServletRequest request) throws AppException {
        User querySalesUser = UserUtil.getCurrentUser();
        SalesReportResultDto result = new SalesReportResultDto();
        //SalesReportResultDto details = new SalesReportResultDto()
        if(querySalesUser!=null){
            salesDto.setUserId(Long.toString(querySalesUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                salesDto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    salesDto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, salesDto.getUserId());
        SimpleDateFormat salesDf = new SimpleDateFormat(YEARMONTHDAY);
        SimpleDateFormat ssalesDf = new SimpleDateFormat(YEARMONTH);
        Calendar salesCal = Calendar.getInstance();
        if(salesDto != null) {
            if(Utils.isNullOrEmpty(salesDto.getTransactionStartDate())){
                if(request.getSession().getAttribute(SALESSTARTDATE) != null){
                    salesDto.setTransactionStartDate(request.getSession().getAttribute(SALESSTARTDATE).toString());
                    }else{
                        salesDto.setTransactionStartDate(ssalesDf.format(salesCal.getTime())+"-01");
                    }
            }
            if(Utils.isNullOrEmpty(salesDto.getTransactionEndDate())){
                if(request.getSession().getAttribute(SALESENDDATE) != null){
                    salesDto.setTransactionEndDate(request.getSession().getAttribute(SALESENDDATE).toString());
                    }else{
                        salesDto.setTransactionEndDate(salesDf.format(salesCal.getTime()));
                    }
            }
            request.getSession().setAttribute(SALESSTARTDATE, salesDto.getTransactionStartDate());
            request.getSession().setAttribute(SALESENDDATE, salesDto.getTransactionEndDate());
            salesDto.setTransactionStartDate(request.getSession().getAttribute(SALESSTARTDATE).toString());
            salesDto.setTransactionEndDate(request.getSession().getAttribute(SALESENDDATE).toString());
            if(Utils.isNullOrEmpty(salesDto.getPackageId()) || "all".equals(salesDto.getPackageId())){
                salesDto.setPackageId("-1");
            }
            if(Utils.isNullOrEmpty(salesDto.getHierarchy())){
                if(request.getSession().getAttribute(SALESHIERARCHY) == null){
                    salesDto.setHierarchy(salesDto.getUserId());
                }else{
                    salesDto.setHierarchy(request.getSession().getAttribute(SALESHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(salesDto.getHierarchy())){
                salesDto.setHierarchy(maintainLogisticDao.getDealers(salesDto.getUserId()));
            }
            request.getSession().setAttribute(SALESHIERARCHY, salesDto.getHierarchy());
            result = reportService.querySalesVolume(salesDto);
        }
        request.getSession().setAttribute(GETSALESREPORTPAGE, salesDto);
        List<LogisticRelatedDto> packages = maintainLogisticDao.getPackageName();
        model.addAttribute(PACKAGELIST, packages);
        List<String> dealers = maintainLogisticDao.getDealerList(salesDto.getUserId());
        model.addAttribute(DEALERLIST, dealers);
        model.addAttribute(RESULTLIST, result.getResult());
        model.addAttribute("searchFlag", "0");
        model.addAttribute("dealerId", salesDto.getUserId());
        //model.addAttribute("newPrePay", result.getPrePayDetails())
        //model.addAttribute("newUsed", result.getUsedDetails())
        //model.addAttribute("newExpire", result.getExpireDetails())
        model.addAttribute("dto", salesDto);
        return SALESREPORT;
    }

    @RequestMapping(value = "/toQuerySalesDetails")
    public String toQuerySalesDetails(ReportQueryDto salesDto, 
        Model model, HttpServletRequest request) throws AppException {
        User querySalesUser = UserUtil.getCurrentUser();
        SalesReportResultDto result = new SalesReportResultDto();
        if(querySalesUser!=null){
            salesDto.setUserId(Long.toString(querySalesUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                salesDto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    salesDto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, salesDto.getUserId());
        if(salesDto != null) {
            if(Utils.isNullOrEmpty(salesDto.getPackageId()) || "all".equals(salesDto.getPackageId())){
                salesDto.setPackageId("-1");
            }
            if(Utils.isNullOrEmpty(salesDto.getHierarchy())){
                if(request.getSession().getAttribute(SALESHIERARCHY) == null){
                    salesDto.setHierarchy(salesDto.getUserId());
                }else{
                    salesDto.setHierarchy(request.getSession().getAttribute(SALESHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(salesDto.getHierarchy())){
                salesDto.setHierarchy(maintainLogisticDao.getDealers(salesDto.getUserId()));
            }
            request.getSession().setAttribute(SALESHIERARCHY, salesDto.getHierarchy());
            result = reportService.querySalesVolumeDetails(salesDto);
        }
        request.getSession().setAttribute(GETSALESREPORTPAGE, salesDto);
        model.addAttribute("notUsed", result.getNotUsedDetails());
        return "/report/salesReportDetails";
    }
    
    @RequestMapping(value = "/toExportSalesReport")
    public ModelAndView toExportSalesReport(ReportQueryDto salesDto,
        Model model, HttpServletRequest request) throws AppException {
        ModelAndView modelAndview = new ModelAndView();
        SalesReportResultDto result = new SalesReportResultDto();
        User querySalesUser = UserUtil.getCurrentUser();
        if(querySalesUser!=null){
            salesDto.setUserId(Long.toString(querySalesUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                salesDto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    salesDto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, salesDto.getUserId());
        if(salesDto != null) {
            if(Utils.isNullOrEmpty(salesDto.getPackageId()) || "all".equals(salesDto.getPackageId())){
                salesDto.setPackageId("-1");
            }
            if(Utils.isNullOrEmpty(salesDto.getHierarchy())){
                if(request.getSession().getAttribute(SALESHIERARCHY) == null){
                    salesDto.setHierarchy(salesDto.getUserId());
                }else{
                    salesDto.setHierarchy(request.getSession().getAttribute(SALESHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(salesDto.getHierarchy())){
                salesDto.setHierarchy(maintainLogisticDao.getDealers(salesDto.getUserId()));
            }
            request.getSession().setAttribute(SALESHIERARCHY, salesDto.getHierarchy());
            result = reportService.exportSalesReport(salesDto);
        }
        request.getSession().setAttribute(GETSALESREPORTPAGE, salesDto);
        
        modelAndview.addObject(CommonConstants.EXPORT_CSV_DATA_LIST,result.getDetails());
        modelAndview.addObject(CommonConstants.EXPORT_CSV_MAPPING_FILE,"exportReportDetails.xml");
        modelAndview.addObject(CommonConstants.EXPORT_CSV_TEMPLATE_NAME,"exportReportDetails");
        modelAndview.setViewName("exportReportDetails");
        return modelAndview;            
    }
    /**
     * 返回查询销售额数据
     */
    @RequestMapping(value = "/backToSalesReportPage")
    public String backToSalesReportPage(Model model, HttpServletRequest request) throws AppException {
        ReportQueryDto preDto = new ReportQueryDto();
        SalesReportResultDto backResult = new SalesReportResultDto();
        User querySalesUser = UserUtil.getCurrentUser();
        if(querySalesUser!=null){
            preDto.setUserId(Long.toString(querySalesUser.getDealerId()));
        }else{
            //MARS 端操作
            if(request.getSession().getAttribute(DEALERID) != null){
                preDto.setUserId(request.getSession().getAttribute(DEALERID).toString());
            }else{
                String dealerIdStr = (String)request.getSession().getAttribute("MARS_DEALERID");
                if(StringUtils.isNotBlank(dealerIdStr)){
                    preDto.setUserId(dealerIdStr);
                    }
            }
        }
        request.getSession().setAttribute(DEALERID, preDto.getUserId());
        if(request.getSession().getAttribute(SALESSTARTDATE) != null){
            preDto.setTransactionStartDate(request.getSession().getAttribute(SALESSTARTDATE).toString());
            }
        if(request.getSession().getAttribute(SALESENDDATE) != null){
            preDto.setTransactionEndDate(request.getSession().getAttribute(SALESENDDATE).toString());
            }
        SimpleDateFormat backDf = new SimpleDateFormat(YEARMONTHDAY);
        SimpleDateFormat sbackDf = new SimpleDateFormat(YEARMONTHDAY);
        Calendar preCal = Calendar.getInstance();
        if(preDto != null) {
            if(Utils.isNullOrEmpty(preDto.getTransactionStartDate())){
                if(request.getSession().getAttribute(SALESSTARTDATE) != null){
                    preDto.setTransactionStartDate(request.getSession().getAttribute(SALESSTARTDATE).toString());
                    }else{
                        preDto.setTransactionStartDate(sbackDf.format(preCal.getTime())+"-01");
                    }
            }
            if(Utils.isNullOrEmpty(preDto.getTransactionEndDate())){
                if(request.getSession().getAttribute(SALESENDDATE) != null){
                    preDto.setTransactionEndDate(request.getSession().getAttribute(SALESENDDATE).toString());
                    }else{
                        preDto.setTransactionEndDate(backDf.format(preCal.getTime()));
                    }
            }
            request.getSession().setAttribute(SALESSTARTDATE, preDto.getTransactionStartDate());
            request.getSession().setAttribute(SALESENDDATE, preDto.getTransactionEndDate());
            preDto.setTransactionStartDate(request.getSession().getAttribute(SALESSTARTDATE).toString());
            preDto.setTransactionEndDate(request.getSession().getAttribute(SALESENDDATE).toString());
            if(Utils.isNullOrEmpty(preDto.getPackageId()) || "all".equals(preDto.getPackageId())){
                preDto.setPackageId("-1");
            }
            if(Utils.isNullOrEmpty(preDto.getHierarchy())){
                if(request.getSession().getAttribute(SALESHIERARCHY) == null){
                    preDto.setHierarchy(preDto.getUserId());
                }else{
                    preDto.setHierarchy(request.getSession().getAttribute(SALESHIERARCHY).toString());
                }
            }else if(DEFAULTHIERARCHY.equals(preDto.getHierarchy())){
                preDto.setHierarchy(maintainLogisticDao.getDealers(preDto.getUserId()));
            }
            request.getSession().setAttribute(SALESHIERARCHY, preDto.getHierarchy());
            backResult = reportService.querySalesVolume(preDto);
        }
        request.getSession().setAttribute(GETMEMBERREPORTPAGE, preDto);
        List<LogisticRelatedDto> backPackages = maintainLogisticDao.getPackageName();
        model.addAttribute(PACKAGELIST, backPackages);
        List<String> dealers = maintainLogisticDao.getDealerList(preDto.getUserId());
        model.addAttribute(DEALERLIST, dealers);
        model.addAttribute(RESULTLIST, backResult.getResult());
        model.addAttribute("searchFlag", "0");
        model.addAttribute("dealerId", preDto.getUserId());
        //model.addAttribute("newPrePay", backResult.getPrePayDetails())
        //model.addAttribute("newUsed", backResult.getUsedDetails())
       // model.addAttribute("newExpire", backResult.getExpireDetails())
        model.addAttribute("dto", preDto);
        return SALESREPORT;
    }
    
    @RequestMapping(value = "/showMemberPackagesForAlldealerReport")
    public String showMemberPackagesForAlldealerReport(MemberQueryDto dto,Model model, HttpServletRequest request) throws AppException {
        List<DealerInfoRelMars> dealerInfoRelMarsList = redemptionService.getMarsTenantIdByDealerId(UserUtil.getCurrentUser().getDealerId());
        List<MemberInfo> memberList = new ArrayList<MemberInfo>();
        if(dealerInfoRelMarsList != null && !dealerInfoRelMarsList.isEmpty()){
            String marsTenantId = dealerInfoRelMarsList.get(0).getMarsTenantId();
            List<Integer> list = redemptionService.getDealerIdByMarsTenantId(marsTenantId);
            if(list != null && !list.isEmpty()){
                for(int i=0;i<list.size(); i++){
                    MemberInfo memberInfo = new MemberInfo();
                    memberInfo = maintainMemberService.getMemberByDealerIdMemberIdMobilePhone(list.get(i).longValue(),dto.getMobilePhone());
                    if(memberInfo != null){
                        memberList.add(memberInfo);
                    }
                }
            }
        }
        if(memberList != null && !memberList.isEmpty()){
            List<MemberPackagesReportOfAllDealerDto> resultForAlldealer = new ArrayList<MemberPackagesReportOfAllDealerDto>();
            for(int i=0; i<memberList.size(); i++){
                MemberPackagesReportOfAllDealerDto memberPackagesReportOfAllDealerDto = new MemberPackagesReportOfAllDealerDto();
                MemberQueryDto memberQueryDto = new MemberQueryDto();
                memberQueryDto.setId(memberList.get(i).getId());
                List<MemberPackagesReportDto> list=redemptionService.getPackageListForReportByMember(memberQueryDto);
                List<MemberAndDealerInfoDto> memberAndDealerInfoDtoList = redemptionService.getMemberAndDealerInfoDtoByMemberId(memberQueryDto.getId());
                MemberAndDealerInfoDto memberAndDealerInfoDto = new MemberAndDealerInfoDto();
                if(memberAndDealerInfoDtoList !=null && !memberAndDealerInfoDtoList.isEmpty()){
                    memberAndDealerInfoDto = memberAndDealerInfoDtoList.get(0);
                }
                memberPackagesReportOfAllDealerDto.setMemberPackagesReportDtoList(list);
                memberPackagesReportOfAllDealerDto.setMemberAndDealerInfoDto(memberAndDealerInfoDto);
                resultForAlldealer.add(memberPackagesReportOfAllDealerDto);
            }
            model.addAttribute("resultForAlldealer", resultForAlldealer);
            model.addAttribute("submitDto", dto);
        }else{
            List<MemberPackagesReportOfAllDealerDto> resultForAlldealer = new ArrayList<MemberPackagesReportOfAllDealerDto>();
            MemberPackagesReportOfAllDealerDto memberPackagesReportOfAllDealerDto = new MemberPackagesReportOfAllDealerDto();
            List<MemberPackagesReportDto> list=redemptionService.getPackageListForReportByMember(dto);
            List<MemberAndDealerInfoDto> memberAndDealerInfoDtoList = redemptionService.getMemberAndDealerInfoDtoByMemberId(dto.getId());
            MemberAndDealerInfoDto memberAndDealerInfoDto = new MemberAndDealerInfoDto();
            if(memberAndDealerInfoDtoList !=null && !memberAndDealerInfoDtoList.isEmpty()){
                memberAndDealerInfoDto = memberAndDealerInfoDtoList.get(0);
            }
            memberPackagesReportOfAllDealerDto.setMemberPackagesReportDtoList(list);
            memberPackagesReportOfAllDealerDto.setMemberAndDealerInfoDto(memberAndDealerInfoDto);
            resultForAlldealer.add(memberPackagesReportOfAllDealerDto);
            model.addAttribute("resultForAlldealer", resultForAlldealer);
            model.addAttribute("submitDto", dto);
            com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto memberQueryDto = 
                (com.cap.bts.crmdp.dealer.member.dto.MemberQueryDto) request.getSession().getAttribute("getMaintainMemberPage");
            if(memberQueryDto != null){
                memberQueryDto.setIsSelected("radio"+ dto.getId() +dto.getCarPlate() +"Rad");
            }
        }
        return "/report/showMemberPackagesReportForAllDealer";
    }
}
